package com.blog.serlvet;

import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.User;
import com.blog.dao.BlogDao;
import com.blog.dao.ThumbsUpDao;
import com.blog.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

public class ThumbsUpServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = LoginUtil.checkApiLogin(req.getSession(), resp);
        if (user == null) {
            return;
        }

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        Integer blogId = null;
        try {
            blogId = Integer.valueOf(req.getParameter("id"));
            if (blogId == null) {
                writer.println(JSONObject.toJSONString(new BaseResponse(400, "点赞失败", null)));
                return;
            }
        } catch (Exception e) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "点赞失败", null)));
            return;
        }

        ThumbsUpDao thumbsUpDao = new ThumbsUpDao();
        BlogDao blogDao = new BlogDao();
        try {
            if (thumbsUpDao.select(blogId, user.getId())) {
                writer.println(JSONObject.toJSONString(new BaseResponse(400, "您已经点过赞", null)));
                return;
            }

            // 插入点赞信息
            thumbsUpDao.thumbsUp(blogId, user.getId());
            // 更新点赞数
            blogDao.thumbsUp(blogId);
            writer.println(JSONObject.toJSONString(new BaseResponse(200, "点赞成功", null)));
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(500);
        }

    }
}
